# -*- coding: utf-8 -*-

# 
# this is the menu-slot actions, the major file of this framework
#
# Created: Thu Apr 21 12:50:32 2011
#      
#  
#  date                     author          issues
#  2011-Apr-11           Wan            creator
#  2011-May-04          Wan            add menu batch, and delete hard coding for plugins
#
#

"""
Module implementing MainWindow.
"""
import re,  sys, os,  unittest,  imp

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from .Ui_Main import Ui_MainWindow
from .menuBatch import Dialog_MenuBatch

#from .MainLeftWindow import MainLeftWindow
#from .MainRightWindow import MainRightWindow

from .const import globalvar

class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """                   
    def __init__(self, parent = None):
        """
        Constructor
        
        @param parent reference to the parent widget (QWidget)
        """
        QMainWindow.__init__(self, parent)
        self.setupUi(self)
        
        # setting text main browser initial values
        self.textMainBrowser.setHtml("")
        
        # setting text browser initial values
        self.textServerBrowser.setHtml("")

        #@TODO list, now I'm hard coding here, but it will get this configuaration from menue->TestManager->Batch
        # running settings, do I need to save these values to a file?
        # dictionary for  now supports all plugins, this is add by menu -> TestManager->Batch
        self.plugins={'DI': 'C:\\python\\src\\plugin\\di\\di.py',  \
                         'DUU': 'C:\\python\\src\\plugin\\duu\\duu.py',  \
                         'WMC': 'C:\\python\\src\\plugin\\wmc\\wmc.py' 
                         }
        self.currentPlugin=' '
        
        self.pluginsCfg = {}
        
        
        self.verbosity = 1
        self.lastError = 0
        self.properties = {}
        self.automated = {}
        self.interactive = {}
        self.runtimeInfo = {}
        ## dictionary for global options
        self.globalOptions={'Automated':'', \
                                'Iterations':'', \
                                'CpuAffinity':' ', \
                                'Stressers':' ', \
                                'Restart':' ', \
                                'Standby': ' ' ,\
                                'Hibernation': ' ' ,\
                                'MonitorBlanking': ' ' ,\
                                'SusResTimeCal': ' ' ,\
                                'WaiAfterRestart': ' ' ,\
                                'WaitAfterSuspend': ' ' ,\
                                'HaltOnError': ' ' ,\
                                'OnError': ' ' ,\
                                'LoginUser': ' ' ,\
                                'LoginPass': ' ' ,\
                                'LoginDomain': ' ' ,\
                                'Log': ' ' ,\
                                'SummaryLog': ' ' ,\
                                'PackageLogs': ' ' ,\
                                'OnLoadMessage': ' ' 
                                }
        
        
        # get runtime infomation from system
        self.initRuntimeInfo()
        
        # get pci device from enumate system device
        self.initPCIDevices()
                
        # get the test suite from plugins
        self.suite = None   #self.dynamicLoad()
        
        
    def dynamicLoad(self):
        """
        dynamic load test module
        """
        loader = unittest.defaultTestLoader
        suite = unittest.TestSuite()
        for key in self.plugins:
            module = imp.load_source(key.lower(),  self.plugins[key].lower())
            str = "module."+key.lower()+".setUI(unittest, self)"
            exec(str)
                
            suite.addTest(loader.loadTestsFromModule(module))
            
        return suite
            
            
    def initConfigFile(self):
        for key in self.plugins:
            self.pluginsCfg[key] = os.path.splitext(self.plugins[key])[0] + ".cfg"                  
        
        
    def initGlobalOptions(self):
        """
        this is mandatory table
        '"""    
        i = -1
        for key in self.globalOptions:            
            i = i+1
            item = QTableWidgetItem(key)
            self.tblGlobalOptions.setVerticalHeaderItem(i, item)
            item = QTableWidgetItem(self.globalOptions[key])
            self.tblGlobalOptions.setItem(i, 0,  item)            
            
        
    def initProperties(self,  fileName):
        """
        
        '"""    
        if len(self.properties):
            i = -1
            for key in self.properties:            
                i = i+1
                item = QTableWidgetItem(key)
                self.tblProperties.setVerticalHeaderItem(i, item)
                item = QTableWidgetItem(self.tblProperties[key])
                self.tblProperties.setItem(i, 0,  item)
        
        
    def initAutomated(self):
        """
        
        '"""    
        self.automated={' ':' '}
        
        
    def initInteractive(self):
        """
        
        '"""    
        self.interactive={' ':' '}
        
        
    def initRuntimeInfo(self):
        """
        get and set runtime infomation 
        '"""       
        i = -1
        for key in self.runtimeInfo:            
            i = i+1
            item = QTableWidgetItem(key)
            self.tblRuntime.setVerticalHeaderItem(i, item)
            item = QTableWidgetItem(self.tblRuntime[key])
            self.tblRuntime.setItem(i, 0,  item)
        
    def initPCIDevices(self):
        """
        
        '"""    
        pass
        
    def initActions(self):                   
        """
        
        '"""    
        self.api={}
        pass
    
               
    def  printLog(self,  str,  br = '<br>'):
        """
        print log to textMainBrowser, new line in the end is an option
        """
        self.textMainBrowser.append("%s %s"%(str,  br))         
        
    def  printDebug(self,  str,  br = '<br>'):
        """
        print log to textServerBrowser, new line in the end is an option
        """
        self.textServerBrowser.append("%s %s"%(str,  br))
        
    def  analyzeConfigFile(self,  fileName, dic,  sp = ':='):
        """
        this is a common funciton to analyze configure file, 
        1) settings
        2) actions
        """
        self.printDebug(fileName)
        
        self.fileName = fileName        
        lines = []
        try:
            if pattern.length() == 0:
                #let's catch every line that doesn't start with #
                pattern = '^[^#]'
                
            input = open(self.fileName)
            lines = input.readlines()
            input.close()
            
            for line  in lines:
                #for test
                self.printDebug(line)
                
                match = re.search(str(pattern),  line,  re.I)
                if match:
                    tokens = line.split(sp) ## return tokens list, default split is ':='
                    item = tokens[0]
                    value = tokens[1]
                    # insert to properties table?
                    dic[item] = value                    
                    
        except:
            if self.lastError == '' :
                self.lastError = 'Unexpected error: ' + str(sys.exc_info()[1])
                printLog("Unexpect error: ",  sys.exc_info()[0])
                pass


    @pyqtSlot()
    def on_actionAbout_Novatel_Test_Suite_triggered(self):
        """
        show About menu, version, system configuaration, and so on
        """
        self.textMainBrowser.append("########################################################")
        self.textMainBrowser.append("<b>Welcome to use Novatel Automatic Test Suite Tools!</b><br>")
        self.textMainBrowser.append("Author:" + globalvar.__AUTHOR__)
        self.textMainBrowser.append("Email: " + globalvar.__EMAIL__)
        self.textMainBrowser.append("Version:" +  globalvar.__VERSION__ +  "<br>")
        self.textMainBrowser.append("########################################################")
        
        self.textMainBrowser.append("Computer Name:" + globalvar.__COMPUTERNAME__)
        self.textMainBrowser.append("User Domain:" + globalvar.__USERDOMAIN__)
        self.textMainBrowser.append("User Name:" + globalvar.__USERNAME__)
        self.textMainBrowser.append("Logon Server:" + globalvar.__LOGONSERVER__)
        self.textMainBrowser.append("Common Files:" + globalvar.__COMMONPROGRAMFILES__)
        self.textMainBrowser.append("Program Files:" + globalvar.__PROGRAMFILES__)
        self.textMainBrowser.append("System Root:" + globalvar.__SYSTEMROOT__)
        self.textMainBrowser.append("Command Path:" + globalvar.__COMSPEC__)
        self.textMainBrowser.append("Temp Path:" + globalvar.__TEMP__)
        self.textMainBrowser.append("Processor Arch:" + globalvar.__PROCESSOR_ARCHITECTURE__)
        self.textMainBrowser.append("Windows Directory:" + globalvar.__WINDIR__)
        self.textMainBrowser.append("System Driver:" + globalvar.__SYSTEMDRIVE__)
        self.textMainBrowser.append("Processors:" + globalvar.__NUMBER_OF_PROCESSORS__)
        self.textMainBrowser.append("User Profile:" + globalvar.__USERPROFILE__)
        self.textMainBrowser.append("OS:" + globalvar.__OS__)
        self.textMainBrowser.append("Public Path:" + globalvar.__PUBLIC__)        
        
        ## show statusbar message
        self.statusMainBar.showMessage("About Novatel Test Suite %s"%(globalvar.__VERSION__))
        
    @pyqtSlot()
    def on_actionNew_triggered(self):
        """
        menu File->New
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionOpen_triggered(self):
        """
        menu File->Open
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionSave_triggered(self):
        """
        menu File->Save
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionSave_As_triggered(self):
        """
        menu File->Save as
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionPrint_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionPrint_Preview_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionPrint_Setup_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionExit_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionCut_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionCopy_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionPaste_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionRename_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionToolbar_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionStatus_Bar_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionTest_Manager_Bar_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionOptions_Bar_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionGlobal_Information_Bar_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionTest_Plan_Info_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionRun_triggered(self):
        """
        run the plugins we scheduled in "menu->TestManager->Batch"
        """
        self.suite = self.dynamicLoad()
        unittest.TextTestRunner().run(self.suite)
        
        self.printLog("All test cases are done!")
        
    
    @pyqtSlot()
    def on_actionStop_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionPause_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionStep_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionCustom_Test_Suite_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionBatch_triggered(self):
        """
        add or delete plugin here, and get the plugin dictionary we want to run
        """    
        dlg = Dialog_MenuBatch()
        dlg.setupUi(dlg)
        dlg.setUI(self)
        dlg.exec_()    
    
    @pyqtSlot()
    def on_actionSystem_Information_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionPreinstall_Log_Check_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionPackage_Last_Result_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    @pyqtSlot()
    def on_actionOptions_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        raise NotImplementedError
    
    
